package com.zlsy.thread.cas;

/**
 * @author zhouliang
 * @date 2020/8/20 20:46
 * 模拟cas
 */
public class TwoThreadCompation implements Runnable {


    private volatile int value;

    public static void main(String[] args) throws InterruptedException {
        TwoThreadCompation r = new TwoThreadCompation();
        r.value = 0;
        Thread thread1 = new Thread(r,"thrad 1");
        Thread thread2 = new Thread(r,"thread 2");
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(r.value);
    }

    public synchronized int compareAndSwap(int expectValue, int newValue) {
        int oldValue = value;
        if (oldValue == expectValue) {
            value = newValue;
        }
        return oldValue;
    }

    @Override
    public void run() {
        compareAndSwap(0, 1);
    }
}
